package com.neusoft.elmboot.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import com.neusoft.elmboot.mapper.*;
import com.neusoft.elmboot.po.*;
import com.neusoft.elmboot.service.DeliveryAddressService;
import com.neusoft.elmboot.service.ex.DataNotFoundException;
import com.neusoft.elmboot.service.ex.NotEnoughException;
import com.neusoft.elmboot.service.ex.PaymentException;
import com.neusoft.elmboot.service.ex.UpdateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.pulsar.PulsarProperties;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.neusoft.elmboot.service.OrdersService;
import com.neusoft.elmboot.util.CommonUtil;

@Service
public class OrdersServiceImpl implements OrdersService{
	
	@Autowired
	private CartMapper cartMapper;
	@Autowired
	private OrdersMapper ordersMapper;
	@Autowired
	private OrderDetailetMapper orderDetailetMapper;
	@Autowired
	private FoodMapper foodMapper;
	@Autowired
	private DeliveryAddressMapper deliveryAddressMapper;
	@Autowired
	private BusinessMapper businessMapper;

	@Override
	@Transactional
	public int createOrders(Orders orders) {
		//1、查询当前用户购物车中当前商家的所有食品
		Cart cart = new Cart();
		cart.setUserId(orders.getUserId());
		cart.setBusinessId(orders.getBusinessId());
		List<Cart> cartList = cartMapper.listCart(cart);


		//如果购物车为空，返回错误代码-1
		if (cartList.isEmpty()) {
			throw new DataNotFoundException("购物车为空，订单创建失败！");
		}

		//设置总金额、收货地址 达成历史信息不变的目标
		//先计算订单总金额
		double orderTotal = 0;
		for(Cart c : cartList) {
			//获取行锁 查询食品信息
			Food food = foodMapper.getFoodById(c.getFoodId());
			//检查商品库存是否足够
			if (food.getCount() < c.getQuantity()) {
				throw new NotEnoughException("商品库存不足，订单创建失败！");
			}
			orderTotal += food.getFoodPrice() * c.getQuantity();
		}
		orderTotal += businessMapper.getBusinessById(orders.getBusinessId()).getDeliveryPrice();

		orders.setOrderTotal(orderTotal);
		System.out.println(orders.getDaId());
		//设置送货地址
		DeliveryAddress deliveryAddress = deliveryAddressMapper.getDeliveryAddressById(orders.getDaId());
		orders.setDeliveryAddress(deliveryAddress.getAddress());

		//获取自增主键
		orders.setOrderDate(CommonUtil.getCurrentDate());
		ordersMapper.saveOrders(orders);

		int orderId = orders.getOrderId();

		//3、批量添加订单明细
		List<OrderDetailet> list = new ArrayList<>();
		for(Cart c : cartList) {
			OrderDetailet od = new OrderDetailet();
			od.setOrderId(orderId);
			od.setFoodId(c.getFoodId());
			od.setQuantity(c.getQuantity());

			Food food = foodMapper.getFoodById(c.getFoodId());
			od.setFoodName(food.getFoodName());
			od.setFoodPrice(food.getFoodPrice()*od.getQuantity());

			list.add(od);

			//更新食品库存
			food.setCount(food.getCount() - c.getQuantity());

			//获取行锁 更新商品库存
			int result = foodMapper.updateFoodCount(food);
			if(result <= 0) {
				throw new UpdateException ("更新食品库存失败！");
			}

		}
		orderDetailetMapper.saveOrderDetailetBatch(list);
		
		//4、从购物车表中删除相关食品信息

		cartMapper.removeCart(cart);
		
		return orderId;
	}
	@Override
	public List<OrderDetailet> getOrderDetailById(Integer orderId){
		List<OrderDetailet> list = orderDetailetMapper.listOrderDetailetByOrderId(orderId);
		if(list != null && !list.isEmpty()){
			return list;
		}
		else{
			throw new DataNotFoundException("订单没有明细!");
		}
	}

	@Override
	public Orders getOrdersById(Integer orderId) {
		Orders result = ordersMapper.getOrdersById(orderId);
		if(result == null) {
			throw new DataNotFoundException("订单不存在，获取订单失败！");
		}
		return result;
	}
	
	@Override
	public List<Orders> listOrdersByUserId(String userId){
		List<Orders> list = ordersMapper.listOrdersByUserId(userId);
		if(list != null && !list.isEmpty()){
			return list;
		}
		else{
			throw new DataNotFoundException("用户没有订单!");
		}
	}

	@Transactional
	@Override
	public int payOrders(Integer orderId){
		Orders orders = ordersMapper.getOrdersById(orderId);
		if(orders == null) {
			throw new DataNotFoundException("订单不存在，支付失败！");
		}
		if(orders.getOrderState() == 1) {
			throw new PaymentException("订单已支付，不能重复支付！");
		}
		orders.setOrderState(1);
		int result = ordersMapper.payOrders(orders.getOrderId());
		if(result <= 0) {
			throw new UpdateException("支付失败！");
		}
		return result;
	}

	@Override
	public int cancelOrders(Integer orderId){
		Orders orders = ordersMapper.getOrdersById(orderId);
		if(orders == null) {
			throw new DataNotFoundException("订单不存在，取消失败！");
		}
		if(orders.getOrderState() == 2) {
			throw new UpdateException("订单已取消，不能重复取消！");
		}
		if(orders.getOrderState() == 1) {
			throw new UpdateException("订单已支付，不能取消！");
		}
		orders.setOrderState(2);
		int result = ordersMapper.cancelOrders(orders.getOrderId());
		if(result <= 0) {
			throw new UpdateException("取消失败！");
		}
		//取消订单后，食物的库存应该恢复原状
		List<OrderDetailet> orderDetailets = orderDetailetMapper.listOrderDetailetByOrderId(orderId);
		for(OrderDetailet orderDetailet : orderDetailets){
			//获取食品的信息
			Food food = foodMapper.getFoodById(orderDetailet.getFoodId());
			//恢复食物的库存
			food.setCount(food.getCount() + orderDetailet.getQuantity());
			//获取行锁 更新食品库存
			foodMapper.updateFoodCount(food);
		}
		return result;
	}

	@Override
	@Transactional
	@Scheduled(fixedRate =180000)//3 min 方便测试
	public void AutoCancelUnpaidOrders(){
		//获取所有未支付的订单
		List<Orders> unpaidOrders = ordersMapper.getUnpaidOrders();
		for(Orders order : unpaidOrders){
			//检查订单是否超过3分钟
			String time1MinutesAgo = CommonUtil.subtractMinutes(order.getOrderDate(), 1);
			if(order.getOrderDate().compareTo(time1MinutesAgo) < 0){
				//超过3分钟，取消订单
				cancelOrders(order.getOrderId());
				int result = ordersMapper.cancelOrders(order.getOrderId());
				if(result <= 0) {
					throw new UpdateException("自动取消订单失败！");
				}
			}
		}
	}

	@Override
	@Transactional
	public int deleteOrders(Integer orderId){
		Orders orders = ordersMapper.getOrdersById(orderId);
		if(orders == null) {
			throw new DataNotFoundException("订单不存在，删除失败！");
		}
		//删除订单明细
		orderDetailetMapper.deleteOrderDetailet(orderId);
		//删除订单
		int result = ordersMapper.deleteOrders(orderId);
		if(result <= 0) {
			throw new UpdateException("删除订单失败！");
		}
		return result;
	}

}
